package com.cpic.agencysurvey.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

public class LoadDataServlet extends HttpServlet {

	private static final long serialVersionUID = -5039387818247682828L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String query = req.getParameter("query");
		if (query == null || query.trim().length() <= 0) {
			resp.getWriter().write("Parameter query is null");
			return;
		}

		// 2种执行方式，1种是CSV 还有一种是数据库
		// String json = this.readFromCsv();
		// System.out.println(json);
		String json = loadDataByProcedure(query);
		System.out.println(json);

		resp.getWriter().write(json);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

	/*
	 * 使用存储过程查询所有问题数据
	 */
	private String loadDataByProcedure(String sqlQuery) {
		String driver = "oracle.jdbc.driver.OracleDriver";
		String strUrl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
		Statement stmt = null;
		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		JSONArray dataJSON = null;
		String[] types = new String[9];
		List<Object> dataList = new ArrayList<Object>();
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(strUrl, "test", "test");
			pstmt = conn.prepareStatement(sqlQuery);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				types[0] = rs.getString(1);
				types[1] = rs.getString(2);
				types[2] = rs.getString(3);
				types[3] = rs.getString(4);
				types[4] = rs.getString(5);
				types[5] = rs.getString(6);
				types[6] = rs.getString(7);
				types[7] = rs.getString(8);
				types[8] = rs.getString(9);
				JSONArray rowList = new JSONArray(types);
				dataList.add(rowList);
			}
			dataJSON = new JSONArray(dataList);
			// 从缓存中获得输出结果
		} catch (SQLException ex2) {
			ex2.printStackTrace();
		} catch (Exception ex2) {
			ex2.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
					if (stmt != null) {
						stmt.close();
					}
					if (conn != null) {
						conn.close();
					}
				}
			} catch (SQLException ex1) {
			}
		}
		return dataJSON.toString();
	}

	/*
	 * 返回JSON串
	 * 
	 * @return
	 */
	private String readFromCsv() {

		Collection<Object> data = new ArrayList<Object>();

		try {

			InputStream is = this.getServletContext().getResourceAsStream(
					"/agencysurvey/question.csv");
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"GBK"));
			String line = "";
			while (line != null) {
				line = br.readLine(); // 一次读入一行数据
				if (line == null) {
					continue;
				}

				String[] row = line.split(",");
				if (row == null || row.length <= 0) {
					continue;
				}

				// 转换为JSON数组
				JSONArray rowList = new JSONArray(row);
				data.add(rowList);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		// 最后转换为JSON数组
		JSONArray json = new JSONArray(data);

		return json.toString();
	}

}
